package com.zengde.zxfy.controller;

import com.zengde.zxfy.common.Result;
import com.zengde.zxfy.entity.Dept;
import com.zengde.zxfy.service.DeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/depts")
public class DeptController {
    private static final Logger log = LoggerFactory.getLogger(DeptController.class);
    private final DeptService deptService;

    public DeptController(DeptService deptService) {
        this.deptService = deptService;
    }

    @GetMapping
    public Result<List<Dept>> list() {
        try {
            log.info("开始查询部门列表");
            List<Dept> depts = deptService.list();
            log.info("查询到 {} 条部门记录", depts.size());
            return Result.success(depts);
        } catch (Exception e) {
            log.error("查询部门列表失败", e);
            return Result.error("查询部门列表失败：" + e.getMessage());
        }
    }

    @PostMapping
    public Result<Void> add(@RequestBody Dept dept) {
        try {
            log.info("开始添加部门：{}", dept.getName());
            deptService.add(dept);
            return Result.success();
        } catch (Exception e) {
            log.error("添加部门失败", e);
            return Result.error("添加部门失败：" + e.getMessage());
        }
    }

    @PutMapping
        public Result<Void> update(@RequestBody Dept dept) {
        try {
            log.info("开始更新部门，id：{}，新名称：{}", dept.getId(), dept.getName());
            deptService.update(dept);
            return Result.success();
        } catch (Exception e) {
            log.error("更新部门失败", e);
            return Result.error("更新部门失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Integer id) {
        try {
            log.info("开始删除部门，id：{}", id);
            deptService.delete(id);
            return Result.success();
        } catch (Exception e) {
            log.error("删除部门失败", e);
            return Result.error("删除部门失败：" + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public Result<Dept> getById(@PathVariable Integer id) {
        try {
            log.info("开始查询部门，id：{}", id);
            Dept dept = deptService.getById(id);
            if (dept == null) {
                return Result.error("部门不存在");
            }
            return Result.success(dept);
        } catch (Exception e) {
            log.error("查询部门详情失败", e);
            return Result.error("查询部门详情失败：" + e.getMessage());
        }
    }
} 